package cn.nfwx.tv.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.chanlib.widget.TitleBar;

import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseActivity;
import cn.nfwx.tv.controller.AdvertiseController;
import cn.nfwx.tv.widget.HtmlWebView;

public class AdvertiseActivity extends BaseActivity {

    @Override
    protected String activityName() {
        return AdvertiseActivity.class.getSimpleName();
    }

    private static final String KEY_URL = "key_url";
    private static final String KEY_TYPE = "key_type";

    private String mUrl;
    private int type = 0;

    private View mClose;
    private FrameLayout mLayout;
    private SeekBar mSeekBar;
    private HtmlWebView mWebView;
    private TitleBar mTitlebar;
    private AppBarLayout web_abl_appbar;

    public static final int TYPE_START = 0;
    public static final int TYPE_BEFORE = 1;
    public static final int TYPE_PAUSE = 2;
    public static final int TYPE_JIAOBIAO = 3;
    public static final int TYPE_NYQF = 4;

    public static void startActivity(Context context, String url, int type) {
        Intent intent = new Intent(context, AdvertiseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(KEY_URL, url);
        bundle.putInt(KEY_TYPE, type);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, String url) {
        Intent intent = new Intent(context, AdvertiseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(KEY_URL, url);
        bundle.putInt(KEY_TYPE, -1);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getParameter();

        mLayout = findViewById(R.id.web_layout);
        mSeekBar = findViewById(R.id.web_sbr);
        mClose = findViewById(R.id.tv_advertise_close);
        mTitlebar = findViewById(R.id.web_tb_titlebar);
        web_abl_appbar = findViewById(R.id.web_abl_appbar);

        // 创建 WebView
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView = new HtmlWebView(getApplicationContext());
        mWebView.setLayoutParams(params);
        mLayout.addView(mWebView, 0);
        mWebView.setWebChromeClient(new HtmlWebView.BaseWebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // 顶部显示网页加载进度
                mSeekBar.setProgress(newProgress);
            }

            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTitlebar.setTitle(title);
            }
        });
        mWebView.loadUrl(mUrl);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);

        if (type == TYPE_NYQF) {
            mClose.setVisibility(View.GONE);
            web_abl_appbar.setVisibility(View.VISIBLE);
            mTitlebar.setLeftImageResource(R.mipmap.back_titlebar);
            mTitlebar.setSmoothToTopView(mWebView);
            mTitlebar.setLeftImageOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        } else {
            mClose.setVisibility(View.VISIBLE);
            web_abl_appbar.setVisibility(View.GONE);
        }

        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == TYPE_START) {
                    Intent intent = new Intent(AdvertiseActivity.this, HomeActivity.class);
                    startActivity(intent);
                    AdvertiseActivity.this.finish();
                } else {
                    AdvertiseActivity.this.finish();
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁 WebView
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.release();
            mWebView.destroy();
            mWebView = null;
        }
    }

    public void getParameter() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mUrl = bundle.getString(KEY_URL);
            type = bundle.getInt(KEY_TYPE);
        } else {
            mUrl = "http://southtv.cn/";
        }
    }

    //============================= 下面是本 demo  的逻辑代码
    // ======================================================================================

    /**
     * 按目录键，弹出“关闭页面”的选项
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int itemId = item.getItemId();
        switch (itemId) {
            case R.id.close:
                AdvertiseActivity.this.finish();
                return true;
            case R.id.copy:
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                String url = mWebView.getUrl();
                ClipData clipData = ClipData.newPlainText("test", url);
                if (clipboardManager != null) {
                    clipboardManager.setPrimaryClip(clipData);
                    Toast.makeText(getApplicationContext(), "本页网址复制成功", Toast.LENGTH_SHORT).show();
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private long mOldTime;

    /**
     * 点击“返回键”，返回上一层
     * 双击“返回键”，返回到最开始进来时的网页
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mOldTime < 1500) {
                mWebView.clearHistory();
                mWebView.loadUrl(mUrl);
            } else if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                if (type == TYPE_START) {
                    Intent intent = new Intent(AdvertiseActivity.this, HomeActivity.class);
                    startActivity(intent);
                    AdvertiseActivity.this.finish();
                } else {
                    AdvertiseActivity.this.finish();
                }
            }
            mOldTime = System.currentTimeMillis();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
